package com.ruoyi.utils;

import com.ruoyi.common.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Date;

public class DbbackupUtil {

    private static final Logger loger = LoggerFactory.getLogger(DbbackupUtil.class);

    public static void dbbackup(String HOSTIP, String HOSTPORT, String USERNAME, String PASSWORD, String SAVEPATH) {
        loger.debug("数据库备份开始");
        String[] databaseName = {"pss2022", "guoshuiju"};
        String dates = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss");
        String dated = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        for (Object o : databaseName) {
            String savePath=SAVEPATH + "/" + dated;
            String fileName =  o.toString() + dates+".sql";
            System.out.println(SAVEPATH + "/" + dated + "/" + o.toString() + dates+".sql");
            exportDatabaseTool(HOSTIP, USERNAME, PASSWORD, savePath, fileName, o.toString());
        }
    }
    public static void exportDatabaseTool(String hostIP, String userName, String password, String savePath,String fileName, String databaseName) {
        File saveFile = new File(savePath);
        // 如果目录不存在  创建文件夹
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysqldump")/*.append(" --opt")*/.append(" -h").append(hostIP);
        stringBuilder.append(" --user=").append(userName).append(" --password=").append(password).append(" --lock-all-tables=true");
        stringBuilder.append(" --result-file=").append(savePath+fileName).append(" --default-character-set=utf8 ").append(databaseName);
        try {
            Process process = Runtime.getRuntime().exec(stringBuilder.toString());
            // 0 表示线程正常终止。
            if (process.waitFor() == 0) {
                loger.info("数据库备份成功");
            }
        } catch (IOException e) {
            loger.info("数据库备份异常");
            e.printStackTrace();
        } catch (InterruptedException e) {
            loger.info("数据库备份异常");
            e.printStackTrace();
        }
    }

}
